package com.bosssoft.trainee.nontax.controller;

import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bosssoft.trainee.nontax.annotation.UserLoginToken;
import com.bosssoft.trainee.nontax.common.CodeMsg;
import com.bosssoft.trainee.nontax.common.Result;
import com.bosssoft.trainee.nontax.entity.dto.UserDTO;
import com.bosssoft.trainee.nontax.entity.po.User;
import com.bosssoft.trainee.nontax.entity.vo.UserQueryVO;
import com.bosssoft.trainee.nontax.entity.vo.UserVO;
import com.bosssoft.trainee.nontax.service.TokenService;
import com.bosssoft.trainee.nontax.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuqiang
 * @date 2022/6/18 23:14
 */
@Slf4j
@Controller
@RequestMapping("userInfo")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    TokenService tokenService;


    /**
     * 获取用户信息列表，展示在用户信息界面中
     *
     * @return 统一消息
     */
    @ResponseBody
    @UserLoginToken
    @GetMapping("/list")
    public Result<Object> getUserInfo() {

        List<User> list = userService.list();
        List<UserVO> listVo = new ArrayList<>();
        for (User user : list) {
            UserVO userVo = new UserVO();
            BeanUtils.copyProperties(user, userVo);
            listVo.add(userVo);
        }
        Integer id = Integer.valueOf(tokenService.getUserId());
        log.info("当前用户id:{}", id);
        return Result.success(listVo);
    }

    /**
     * 修改
     *
     * @param userVO UserVO
     * @return 统一消息
     */
    @UserLoginToken
    @ResponseBody
    @PostMapping("/updateUser")
    public Result<Object> updateUser(@Valid @RequestBody UserVO userVO) {
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(userVO, userDTO);
        userDTO.setUpdateId(Integer.valueOf(tokenService.getUserId()));
        if (userService.updateUser(userDTO)) {
            return Result.success();
        } else {
            return Result.error(CodeMsg.USER_NOT_EXSIST);
        }
    }

    /**
     * 添加用户
     *
     * @return 统一消息
     */
    @UserLoginToken
    @ResponseBody
    @PostMapping("/insertUser")
    public Result<Object> insertUser(@Valid @RequestBody UserVO userVo) {
        UserDTO userDto = new UserDTO();
        BeanUtils.copyProperties(userVo, userDto);
        //更新人id
        userDto.setUpdateId(Integer.valueOf(tokenService.getUserId()));
        userService.saveUser(userDto);
        return Result.success();
    }

    /**
     * 删除用户
     *
     * @return 统一消息
     */
    @UserLoginToken
    @ResponseBody
    @GetMapping("/delete/{id}")
    public Result<Object> deleteUser(@PathVariable("id") Integer id) {

        User user = userService.getById(id);
        if (user == null) {
            return Result.error(CodeMsg.USER_NOT_EXSIST);
        } else {
            userService.removeById(id);
            return Result.success();
        }
    }

    /**
     * 查询根据id
     *
     * @return 统一消息
     */
    @UserLoginToken
    @ResponseBody
    @GetMapping("/find/{id}")
    public Result<Object> findById(@PathVariable("id") Integer id) {

        User user = userService.getById(id);
        UserVO userVo = new UserVO();
        if (user == null) {
            return Result.error(CodeMsg.USER_NOT_EXSIST);
        } else {
            BeanUtils.copyProperties(user, userVo);
            return Result.success(userVo);
        }
    }


    /**
     * 多条件+模糊查询
     *
     * @param userQueryVO
     * @return
     */
    @UserLoginToken
    @ResponseBody
    @GetMapping("/findUser")
    public Result<Object> findUser(@RequestBody UserQueryVO userQueryVO) {

        List<UserDTO> list = userService.findUser(userQueryVO);
        if (list.isEmpty()) {
            return Result.error(CodeMsg.USER_NOT_EXSIST);
        } else {
            List<UserVO> userVOList = new ArrayList<>();
            for (UserDTO userDTO : list) {
                UserVO userVO = new UserVO();
                BeanUtils.copyProperties(userDTO, userVO);
                userVOList.add(userVO);
            }
            return Result.success(userVOList);
        }
    }

    /**
     * 分页
     *
     * @param pageNum  pageNum
     * @param pageSize pageSize
     * @return result
     */
    @ResponseBody
    @GetMapping("/test")
    public Result<Object> getUserList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                      @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        List<UserDTO> list = userService.getListDTO(pageNum, pageSize);
        List<UserVO> listVO = new ArrayList<>();
        for (UserDTO userDTO : list) {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(userDTO, userVO);
            listVO.add(userVO);
        }
        Page<User> pageInfo = new Page<>(pageNum, pageSize);
        userService.page(pageInfo);

        Map<String, Object> map = new HashMap<>();
        map.put("role", listVO);
        map.put("pages", pageInfo.getPages());
        map.put("total", pageInfo.getTotal());
        map.put("currentPage", pageInfo.getCurrent());

        return Result.success(map);
    }


    /**
     * 登录验证
     *
     * @param user     表单提交的User
     * @param response HttpServletResponse
     * @return 统一消息
     */
    @ResponseBody
    @GetMapping("/login")
    public Result<Object> login(User user, HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();
        //获取用户账号密码
        User userForBase = new User();
        userForBase.setUserId(userService.findByUserAccount(user).getUserId());
        userForBase.setUserAccount(userService.findByUserAccount(user).getUserAccount());
        userForBase.setUserPassword(userService.findByUserAccount(user).getUserPassword());
        //判断账号或密码是否正确
        if (!userForBase.getUserPassword().equals(user.getUserPassword())) {
            return Result.error(CodeMsg.USER_OR_PASS_ERROR);
        } else {
            String token = tokenService.getToken(userForBase);
            try {
//                jsonObject.put过时，改用set
                jsonObject.set("token", token);
                //获取菜单
                jsonObject.set("menu", userService.getMenu(userForBase.getUserId()));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            response.addCookie(cookie);
            return Result.success(jsonObject);
        }
    }

}
